package com.comando.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.springframework.beans.factory.annotation.Autowired;

import com.comando.dto.UserDto;
import com.comando.service.LoginService;
import com.comando.util.CookieUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 * cookie拦截器
 * 
 * 
 */
public class LoginInterceptor extends MethodFilterInterceptor {

	private static final Logger logger = Logger.getLogger(LoginInterceptor.class);
	public static final String USER_SESSION_KEY = "uid";
	
	private LoginService loginService;

	public LoginService getLoginService() {
		return loginService;
	}

	@Autowired
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	@Override
	protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
		ActionContext ctx = actionInvocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ctx
				.get(StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ctx
				.get(StrutsStatics.HTTP_RESPONSE);
		Map session = ctx.getSession();  
		
        if (session != null && session.get(USER_SESSION_KEY) != null){  
            return actionInvocation.invoke(); 
        }
		/*
		String userNameCookieValue = CookieUtil.getCookie(request, "_username");
		if(StringUtils.isNotBlank(userNameCookieValue)) {
			return actionInvocation.invoke(); 
		}
		*/
		String loginCookieValue = CookieUtil.getCookie(request, "_qunawan");		
		if (StringUtils.isNotBlank(loginCookieValue)) {
			String[] split = loginCookieValue.split(",");
			String username = split[0];
			String password = split[1];
			UserDto userDto = new UserDto();
			userDto.setLoginName(username);
			userDto.setEmail(username);
			userDto.setPassword(password);
			UserDto u = loginService.login(userDto);
			if (u != null) {
				String domain = request.getServerName();
				CookieUtil.addCookie(response, "_username", u.getLoginName(), domain, -1);
				session.put(USER_SESSION_KEY, u.getUserId());// 添加用户到session中
			} else {
				//return "login";
			}
       
        } else {
        	//return "login";
        }
		return actionInvocation.invoke();
	}
	
}

